import React, { useState, useEffect, useRef } from 'react';
import { Toast, Dialog, Input, Popup, TextArea } from 'antd-mobile'
import { CloseOutline } from 'antd-mobile-icons'
import HeadTop from '@/components/HeadTop';
import FootButton from '@/components/FootButton';
import PickerSelect from '@/components/PickerSelect';
import PickerSelectMore from '@/components/PickerSelectMore';
import UploadPhotos from '@/components/UploadPhotos';
import Index from '@/api/handTasks';
import "./index.less"

function Detail(props) {
    const [detaiObj, setDetaiObj] = useState({ itemVoList: [] });
    const [sureButtonTxt, setSureButtonTxt] = useState("开始设备维修")
    const [basicColumns, setbasicColumns] = useState([]);  // 故障类别
    const [basicColumns2, setbasicColumns2] = useState([]); //参数变更
    const [basicColumns3, setbasicColumns3] = useState([]); //产品验证状态
    const [interimMeasure, setInterimMeasure] = useState(); //临时措施
    const [everlastingMeasures, setEverlastingMeasures] = useState(); //永久措施

    const [faultCategory, setfaultCategory] = useState();  //故障类别
    const [paramChange, setparamChange] = useState(); //参数变更
    const [productValidationStatus, setproductValidationStatus] = useState(); //产品验证状态

    const [repairContent, setRepairContent] = useState('');   //维修内容 
    const [value, setValue] = useState(1)

    // 备件备品
    const [visible, setVisible] = useState(false)
    const [checkItems, setCheckItems] = useState([])
    const uploadRef = useRef()
    const uploadRef2 = useRef()

    useEffect(() => {

        // 获取详情
        getInfoDetail()

        // 获取字典
        getDicSelectData()

    }, []);

    const getDicSelectData = () => {
        Promise.all([getDicInfo('FAULT_CATEGORY'), getDicInfo('WHETHER'), getDicInfo('PRODUCT_VALIDATION_STATUS')]).then(res => {
            setbasicColumns([res[0]])
            setbasicColumns2([res[1]])
            setbasicColumns3([res[2]])
        })
    }

    const getDicInfo = (key) => {
        return new Promise((resolve, reject) => {
            Index.dictDetails({
                dictCode: key
            }).then(res => {
                if (res.data.code == 0) {
                    resolve(res.data.data.records)
                } else {
                    reject()
                }
            })
        })
    }

    const setSelectVal = (val) => {
        setfaultCategory(val[0])
    }
    const setSelectVal2 = (val) => {
        setparamChange(val[0])
    }
    const setSelectVal3 = (val) => {
        setproductValidationStatus(val[0])
    }

    const getInfoDetail = () => {
        Index.devicedetail(props.location.state.no).then(res => {
            if (res.data.code) {
                Toast.show({
                    content: '请求失败:' + res.data.msg,
                })
                return
            }
            setDetaiObj(res.data.data)
            uploadRef.current && uploadRef.current.setPhotoListFinish(res.data.data?.photoUrl || [])
            if (res.data.data.status == 'REPAIRING') {
                setSureButtonTxt("确认完成维修")
            }
        })
    }

    const getSubmitSure = () => {
        if (detaiObj.status == 'REPAIRING') {
            if (!faultCategory) {
                Toast.show({
                    content: '请选择故障类别',
                })
                return
            }
            if (!paramChange) {
                Toast.show({
                    content: '请选择参数别更',
                })
                return
            }
            if (!productValidationStatus) {
                Toast.show({
                    content: '请选择产品验证状态',
                })
                return
            }
            if (!repairContent) {
                Toast.show({
                    content: '请输入故障原因',
                })
                return
            }
            if (uploadRef2.current.photoList.length < 1) {
                Toast.show({
                    content: '请上传维修图片',
                })
                return
            }

            console.log(value,'val')
            if(!value || value < 1 ){
                Toast.show({
                    content: '请输入维修人员数量',
                })
                return
            }

        }
        let txt = detaiObj.status == 'ACCEPTED' ? '确定开始维修' : '确定完成维修'
        Dialog.confirm({
            content: txt,
            onConfirm: async () => {
                handleSubmit()
            },
        })
    }

    const handleSubmit = async () => {
        let params = detaiObj.no
        let api = Index.repairing
        if (detaiObj.status == 'REPAIRING') {
            api = Index.repair
            let idxs = checkItems.map(el => el.no) || []
            params = {
                ...detaiObj,
                faultCategory,
                paramChange,
                productValidationStatus,
                interimMeasures: interimMeasure,
                everlastingMeasures,
                sparePartsNo: idxs.join(","),
                signOneUrl: uploadRef2.current ? uploadRef2.current.photoList.join(",") : '',
                repairContent,
                number:value
            }
        }
        api(params).then(res => {
            if (res.data.code) {
                Toast.show({
                    content: '请求失败:' + res.data.msg,
                })
                return
            }
            Toast.show({
                content: res.data.msg,
            })
            getSubmitCancel()
        })
    }

    const getSubmitCancel = () => {
        props.history.goBack(-1)
    }

    const submitModal = (items) => {
        setVisible(false)
        setCheckItems(prev => {
            return [
                ...prev,
                ...items
            ]
        })
    }

    const closePartsLists = (e) => {
        e.stopPropagation()
        setCheckItems([])
    }

    return (
        <div className='page-wrapper halltaskdetail'>
            <HeadTop title="设备维修" history={props.history}></HeadTop>
            <div className="page-body">
                <div className="info">
                    <div className="d-title">维修编号:{detaiObj.no}</div>
                    <div className="info-main">
                        <div className="m-line">
                            <div className="m-name">设备类型：</div>
                            <div className="m-val">{detaiObj.deviceType}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">设备编号：</div>
                            <div className="m-val">{detaiObj.deviceCode}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">设备名称：</div>
                            <div className="m-val">{detaiObj.deviceName}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">维修人员：</div>
                            <div className="m-val">{detaiObj.name}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">报修时间：</div>
                            <div className="m-val">{detaiObj.createTime}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">标准维修时间/分钟</div>
                            <div className="m-val">{detaiObj.standardRepairTime}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">设备位置</div>
                            <div className="m-val">{detaiObj.deviceLocation}</div>
                        </div>
                    </div>
                </div>
                <div className="info">
                    <div className="d-title">设备故障描述</div>
                    <div className="reason">
                        {detaiObj.badReason}
                    </div>
                </div>
                <div className="info">
                    <div className="d-title">故障图片</div>
                    <UploadPhotos
                        ref={uploadRef}
                        detaiObj={detaiObj}
                    />
                </div>
                {
                    // REPAIRING
                    detaiObj.status == "REPAIRING" ?
                        <>
                            <div className="info">
                                <div className="d-title">故障类型</div>
                                <PickerSelect
                                    placeholderTxt="请选择故障类型"
                                    basicColumns={basicColumns}
                                    setSelectVal={setSelectVal}
                                    defaultValue='原辅材料因素'
                                ></PickerSelect>
                            </div>
                            <div className="info">
                                <div className='d-title'>设备故障原因</div>
                                <TextArea
                                    style={{
                                        '--placeholder-color': "#333"
                                    }}
                                    className='select-line'
                                    placeholder='请输入设备故障原因'
                                    value={repairContent}
                                    type="textarea"
                                    onChange={val => {
                                        setRepairContent(val)
                                    }}
                                />
                            </div>

                            <div className="info">
                                <div className="d-title">参数变更</div>
                                <PickerSelect
                                    placeholderTxt="请选择参数变更"
                                    basicColumns={basicColumns2}
                                    setSelectVal={setSelectVal2}
                                    defaultValue='N'
                                ></PickerSelect>
                            </div>

                            <div className="info">
                                <div className="d-title">产品验证状态</div>
                                <PickerSelect
                                    placeholderTxt="请选择产品验证状态"
                                    basicColumns={basicColumns3}
                                    setSelectVal={setSelectVal3}
                                ></PickerSelect>
                            </div>

                            <div className="info">
                                <div className="d-title">临时措施</div>
                                <TextArea
                                    className="info-input"
                                    placeholder='请输入临时措施'
                                    style={{
                                        '--placeholder-color': '#666',
                                        height: 80
                                    }}
                                    value={interimMeasure}
                                    onChange={val => {
                                        setInterimMeasure(val)
                                    }}
                                />
                            </div>
                            <div className="info">
                                <div className="d-title">永久措施</div>
                                <TextArea
                                    className="info-input"
                                    style={{
                                        '--placeholder-color': '#666',
                                        height: 80
                                    }}
                                    placeholder='请输入永久措施'
                                    value={everlastingMeasures}
                                    onChange={val => {
                                        setEverlastingMeasures(val)
                                    }}
                                />
                            </div>
                            <div className="info">
                                <div className="d-title">备件备品领用</div>
                                <div className="show-device-list info-input" style={{ paddingLeft: 10, height: 37 }} onClick={() => setVisible(true)}>

                                    {
                                        checkItems.length ?
                                            checkItems.map(el =>
                                                <span key={el.id}>{el.no},</span>,
                                            ) : <span>请选择备件备品领用</span>

                                    }
                                    {
                                        checkItems.length ? <div className='closeIcon' onClick={e => closePartsLists(e)}>
                                            <CloseOutline />
                                        </div> : null
                                    }

                                </div>
                            </div>

                            <div className="info">
                                <div className="d-title">上传维修照片</div>
                                <UploadPhotos
                                    ref={uploadRef2}
                                    detaiObj={detaiObj}
                                    showUpload="REPAIRING" />
                            </div>

                            <div className="info">
                                <div className="d-title">维修人员数量</div>
                                <Input
                                    className='bc'
                                    placeholder='请输入维修人员数量'
                                    value={value}
                                    onChange={val => {
                                        setValue(val)
                                    }}
                                />
                            </div>

                        </>
                        : null
                }

            </div>

            <FootButton cancelTxt="返回"
                sureTxt={sureButtonTxt}
                getSubmitCancel={getSubmitCancel}
                getSubmitSure={getSubmitSure}></FootButton>

            {/* 备件 列表 */}
            <Popup
                className='select-more-picker'
                visible={visible}
                onMaskClick={() => {
                    setVisible(false)
                }}
                bodyStyle={{ height: '60vh' }}
            >
                <PickerSelectMore
                    close={() => setVisible(false)}
                    submit={submitModal}></PickerSelectMore>
            </Popup>

        </div>
    );
}

export default Detail;
